<?php
namespace Wap\Controller;
class TradingController extends WapController{
	 public function _initialize(){
		parent::_initialize();	
	}

	public function indexguoguo(){
	    $this->display();
	}
	public function indexggadmin(){
	    $sql = "select * from sp_gg";
	    $data = M("gg")->select();

        $this->assign( "data", $data );
//        print_r( $data );
//        $data['heyue'] = '6';
//        $data['fangxiang'] = '6';
//        $data['time'] = '6';
//        $data['dj'] = '6';
//        $data['ylzk'] = '6';
//        $data['zt'] = '6';
//        M("gg")->add( $data );
//        echo M("gg")->getLastSql();
	    $this->display( );
	}

	public function indexggsave(){

	}

	public function indexggdelete(){

	}

	public function deal_zyq(){
		
		$amount = I('amount');
		$user =M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
		if($user['xulimoney'] <$amount*0.1){
			$data['status']=0;
			$data['info']='增益券金额不足';
		}else{
			$data['status']=1;
			$data['info']='已勾选使用增益券';
			$_SESSION['user_zyj']=1;
		}

		$this->ajaxReturn($data);
	}


    /*  把汇率存储进数据库*/
	public function getchangerateapi(){
	    $change = rmbus();

        $result = array();
        $result['rate'] = $change['rate'];
        $result['realtime'] = strtotime( $change['update'] );
        $result['savetime'] = time();
        if( $id = M('changerate')->add($result) )
        {
        }

	}
	/*ajax返回汇率*/
	public function getchangerate(){
          $lastData = M('changerate')->order('realtime desc')->limit(1)->select();
          if( $lastData[0]['rate'] )
          {
             $this->ajaxReturn( $lastData[0]['rate'] *10 );
          }else{
            $this->ajaxReturn( 6.6651 * 10 );
          }
	}


    public function getgolddata(){
        $url = "http://hq.sinajs.cn/list=hf_GC";
        $webdata = \Spark\Util\HttpClient::curlGet($url);

        $pattern = '#"(.*?)"#i';

        preg_match_all($pattern, $webdata, $matches);
        $data0 = $matches[1][0];
        $ary = array();
        $ary = explode( ",", $data0 );
//	print_r( $ary );
//exit;
        /*
        0 最新价
        1 涨幅
        2 买价
        3 卖价
        4 最高价
        5 最低价
        6 时间
        7 昨结算
        8 开盘价       */
        $data['type'] = 2;
//        $data['exchange'] = $change;
        $data['savetime'] = time();
        $data['price'] = $ary[0];
        $data['openingprice'] = $ary[8];
        $data['closeprice'] = $ary[7];
        $data['hightest'] = $ary[4];
        $data['lowest'] = $ary[5];

        $data['realtime'] = strtotime( $ary[12].$ary[6] );

        /*搜索这个realtime是不是和上一条记录一样*/
       // $sql = "select id from sp_price where realtime = ".$data['realtime']." and type = 2 order by realtime desc limit 0,1";
       // $result = M('price')->query( $sql );

       // if( count( $result ) > 0 )
        //{
            /*这条数据并没有更新，给一个随机数*/
          //  $a1=range(1,10);
          //  shuffle($a1);
          //  $a2 = sprintf( "0.2f%", $a1 );
          //  $a3 = rand( 1,2 );
//print_r($a3);echo "<br/>";
           // switch( $a3 ){
             //   case 1:
                   //$data['price'] = $data['price'] + $a2;
               //    break;
               // case 2:
                   //$data['price'] = $data['price'] - $a2;
                 //  break;
               // default:
           // }
       // }
 //       echo $data['price'];
//print_r($ary);
//echo "<br/>";
//print_r($data);
        $id = M('price')->add($data);
  //       echo $id;
//echo "<br/>";
//echo M("price")->getLastSql();
    }

    public function getbtc(){
        $url = "https://www.okcoin.cn/api/v1/ticker.do?symbol=btc_cny";
        $webdata0 = \Spark\Util\HttpClient::curlGet($url);
        $webdata = json_decode( $webdata0, true );

        $data = array();

        if( $webdata )
        {
            if( $webdata['ticker'] )
            {
                if( $webdata['ticker']['buy'] )
                {
//                    $changerate = rmbus();
//                    $changerate = $changerate['rate'];

                    $data['type'] = 3;
                    $data['savetime'] = time();
                    $data['price'] = $webdata['ticker']['buy'];
//                    $data['hightest'] = $webdata['ticker']['high'];
//                    $data['lowest'] = $webdata['ticker']['buy'];
//                    $data['price'] = $webdata['ticker']['buy'];
                    $data['realtime'] = $webdata['date'];
                    $id = M('price')->add($data);
                }
            }
        }
    }

    public function goldchartdata1(){
        $j = 0;
        if( $_POST['type'] )
        $min = $_POST['type'];
        if( $_GET['type'] )
        $min = $_GET['type'];

        if( !$min )
        {
            $min = 1;
        }

        $newdata = array();
        /*黄金的MIN线数据*/
        /* 如果是30MIN线, 时间间隔是20个30分钟 ，600分钟*/
        $sql = "select * from sp_price where savetime between ".(time()-60*20*$min)." and ".time()." and price is not null and type = 2 order by savetime";

//        $this->ajaxReturn( $sql );
        $list = M("price")->query( $sql );


        $data1[0] = self::util(  $list, $min, 0 );
        $data1[1] = self::util(  $list, $min, 1 );
        $data1[2] = self::util(  $list, $min, 2 );
        $data1[3] = self::util(  $list, $min, 3 );
        $data1[4] = self::util(  $list, $min, 4 );
        $data1[5] = self::util(  $list, $min, 5 );
        $data1[6] = self::util(  $list, $min, 6 );
        $data1[7] = self::util(  $list, $min, 7 );
        $data1[8] = self::util(  $list, $min, 8 );
        $data1[9] = self::util(  $list, $min, 9 );
        $data1[10] = self::util(  $list, $min, 10 );
        $data1[11] = self::util(  $list, $min, 11 );
        $data1[12] = self::util(  $list, $min, 12 );
        $data1[13] = self::util(  $list, $min, 13 );
        $data1[14] = self::util(  $list, $min, 14 );
        $data1[15] = self::util(  $list, $min, 15 );
        $data1[16] = self::util(  $list, $min, 16 );
        $data1[17] = self::util(  $list, $min, 17 );
        $data1[18] = self::util(  $list, $min, 18 );
        $data1[19] = self::util(  $list, $min, 19 );



        $result['data'] = $data1;
        $result['channel'] = $min."goldK";
        $this->ajaxReturn( json_encode( $result ) );
    }

    /*获得当前的黄金价格*/
    public function getCurGoldPrice(){
           $sql = "select price from sp_price where type = 2 order by savetime desc limit 0,1";     
           $data = M("price")->query( $sql );
           if( $data[0] )
           {
                if( $data[0]['price'] )
                {
                    echo $data[0]['price'];
                }else{
                    echo "0";
                }
           }else{
                echo "0";
           }
    }

    /*获得当前的比特币价格*/
    public function getCurBtcPrice(){
        $result = array();
        $sql = "select savetime,price from sp_price where type = 3 order by savetime desc limit 0,1";
        $data = M("price")->query( $sql );
        if( $data[0] )
        {
            if( $data[0]['price'] )
            {
//                echo $data[0]['price'];
                $result['ticker']['buy'] = $data[0]['price'];
                $result['ticker']['date'] = $data[0]['savetime'];
            }else{
                echo "0";
            }
        }else{
            echo "0";
        }
        $this->ajaxReturn( $result );
    }

    public function testtest(){
        $a1 = 45.123456789;
        $a2 = sprintf( "0.6f%", $a1 );
        echo $a1;
    }


    private function util( $list, $min, $j ){
        $result = array();
        $i = 0;
        $k = 0;

        $result[0] = (time()-60*(20-$j-0.5)*$min )*1000;
        $result[1] = 0;//openingprice
        $result[2] = 0;//hightest
        $result[3] = 0;//lowest
        $result[4] = 0;//closeprice

        for( $k = 0; $k <  count( $list ); $k++ ){
            if( ($list[$k]['savetime'] > (time()-60*(20-$j)*$min ) )
                &&
                ($list[$k]['savetime'] < (time()-60*(20-$j-1)*$min ) )
            )
            {
                /*1个小的时间区间*/
                if( $i == 0 )
                {
                    $result[1] = $list[$k]['price'];
                    $result[2] = $list[$k]['price'];
                    $result[3] = $list[$k]['price'];
                }
                if( $i == count( $list )-1 )
                {
                    $result[4] = $list[$k]['price'];
                }else{
                    if( $list[$k]['price'] > $result[2] )
                    {
                        $result[2] = $list[$k]['price'];
//                        echo $list[$k]['price'];
//                        echo "<br/>";
//                        echo $k;
//                        echo "<br/>";
                    }

                    if( $list[$k]['price'] < $result[3] )
                    {
                        $result[3] = $list[$k]['price'];
//                        echo $list[$k]['price'];
//                        echo "<br/>";
//                        echo $k;
//                        echo "<br/>";
                    }
                }
                $i++;

                /*判断小的时间区间是否结束*/
                if( $k < count($list)-1 )
                {
                    if( $list[$k+1]['savetime'] >= (time()-60*(20-$j-1)*$min ) )
                    {
                        /*说明这是这个时间区间内的最后一条数据*/
                        $result[4] = $list[$k]['price'];
                        return $result;
                    }
                }else if( $k == count($list)-1  )
                {
                        /*说明这是这个时间区间内的最后一条数据*/
                        $result[4] = $list[$k]['price'];
                        return $result;
                }
            /*1个小的时间区间循环结束*/
            }
        }

        return $result;
    }




    public function silver(){
        $data = array();

        $url = "http://api.jisuapi.com/silver/bank?appkey=ba910abdc0d13bd4";
        $webdata = \Spark\Util\HttpClient::curlGet($url);
        $ret = json_decode($webdata);

    

        $change = getsqlrmb();
        if( is_object( $ret ) )
        {
            $array = (array)$ret;
            if( $array['status'] == '0' )
            {
                foreach( $array['result'] as $key=>$value )
                {
                    $datawhole = (array) $array['result'][$key];
                    if( $datawhole['type'] == "美元账户白银" )
                    {
                        $data['type'] = 1;
                        $data['exchange'] = $change;
                        $data['savetime'] = time();
                        $data['price'] = $datawhole['buyprice'] * $change;
                        $data['openingprice'] = $datawhole['openingprice'] * $change;
                        $data['closeprice'] = $datawhole['lastclosingprice'] * $change;
                        $data['hightest'] = $datawhole['maxprice'] * $change;
                        $data['lowest'] = $datawhole['minprice'] * $change;
                        $data['realtime'] = strtotime( $datawhole['updatetime'] );
                        $id = M('price')->add($data);
                    }
                }

            }
        }
    }


    /*传参数表示1M图或者5M，15M，30M 图*/
    public function web_get_silver(){
        $silverLastData = M('price')->order('realtime desc')->limit(1)->select();
        $array = array();
        $array['_time'] = date("Y-m-d H:i:s");
        $array['_code'] = "CMGCA0";
        $array['_open'] = number_format($silverLastData[0]['openintprice'],2);
        $array['_hightest'] = number_format($silverLastData[0]['hightest'],2);
        $array['_lowest'] = number_format($silverLastData[0]['lowest'],2);
        $array['_curprice'] = number_format($silverLastData[0]['price'],2);

        $option = $_GET['option'];
        if( $option == NULL || $option == "" )
        {
            echo json_encode( $array );
            exit();
        }
        $array['K'] = web_get_silverK($option);
        echo json_encode( $array );
    }

    public function btcminmindata(){
        /*1800秒 200条数据， 9秒1条*/
        $value = array();
        $time = array();
        $result['_max'] = 0;
        $result['_min'] = 99999999;
//        $sql = "select * from sp_price where type = 3 and price is not null and savetime between ".(time() - 30*60)." and ".time()." order by savetime";
        $sql = "select * from sp_price where type = 3 and price is not null and savetime between ".(time() - 200*60)." and ".time()." order by savetime";
//        echo $sql;
//        exit;
        $kdataTotal = M('price')->query( $sql );

//        print_r( $kdataTotal );
//
//        exit;

        for( $i = 0; $i < count( $kdataTotal ); $i++ )
        {
            if( $kdataTotal[$i]['price'] > $result['_max'] )
            {
                $result['_max'] = $kdataTotal[$i]['price'];
            }
            if( $kdataTotal[$i]['price'] < $result['_min'] )
            {
                $result['_min'] = $kdataTotal[$i]['price'];
            }
            $value[$i] = $kdataTotal[$i]['price'];
            $time[$i] = date( "H:i", $kdataTotal[$i]['savetime']);
        }
        $result['value'] = $value;
        $result['time'] = $time;
//        echo json_encode( $array );
//        print_r( $result );
        $this->ajaxReturn( $result );
    }


    /*黄金分时图 美燃油*/
    public function web_get_silver2(){
        /*黄金的价格数据，1秒一条，一共200条,走势图第一张*/
         /*1800秒 200条数据， 9秒1条*/
        $value = array();
        $time = array();
        $result['_max'] = 0;
        $result['_min'] = 99999999;
//        $sql = "select * from sp_price where type = 3 and price is not null and savetime between ".(time() - 30*60)." and ".time()." order by savetime";
        $sql = "select * from sp_price where type = 2 and price is not null and savetime between ".(time() - 200*60)." and ".time()." order by savetime";
//        echo $sql;
//        exit;
        $kdataTotal = M('price')->query( $sql );

//        print_r( $kdataTotal );
//
//        exit;

        for( $i = 0; $i < count( $kdataTotal ); $i++ )
        {
            if( $kdataTotal[$i]['price'] > $result['_max'] )
            {
                $result['_max'] = $kdataTotal[$i]['price'];
            }
            if( $kdataTotal[$i]['price'] < $result['_min'] )
            {
                $result['_min'] = $kdataTotal[$i]['price'];
            }
            $value[$i] = $kdataTotal[$i]['price'];
            $time[$i] = date( "H:i", $kdataTotal[$i]['savetime']);
        }
        $result['value'] = $value;
        $result['time'] = $time;
//        echo json_encode( $array );
//        print_r( $result );
        $this->ajaxReturn( $result );
    }

    /*只需要返回K线图*/

    function web_get_silver3(){
        $option = $_GET['option'];
        $result['K'] = web_get_silverK($option);

        echo json_encode( $result );
    }

	

	public function index(){
		//判断是否有渠道标识
		$channelSign = isset($_GET['channelSign']) ? $_GET['channelSign'] : '';
		if(isset($channelSign) && $channelSign != ''){
			cookie('channelSign',$channelSign);
		}
		//echo cookie('channelSign').'-PsychoTest';
		$time = date("Y-m-d H:i:s");
        $this->assign("wholetime", $time);

		$is_week = in_array(date("w"), array(0,6))?1:0;
		$this->assign('is_week',$is_week);

		$user = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();

//		if( $user == null )
//		{
//		    $user['headimgurl'] = "{:RES}/jinrong/Mobile/Public/images/nan.png";
//		}


		$this->assign('user',$user);

        $time = date("H:i:s");
        $this->assign("nowtime", $time);


        /*首页的最近成交列表数据  15条*/
        $ary1 = array();
        for( $i = 14; $i >= 0; $i -- )
        {
            $ary1[$i]['time'] = date("H:i:s", time()-30*$i );
            $c1 = rand(1,10);
            $c2 = rand(1,10);
            $c3 = rand(1,10);
            $c4 = rand(1,10);
            $c5 = rand(1,10);
            $d0 = date('w');
            $ary1[$i]['capital']="比特币";
            if( ( $d0 != 0 ) && ( $d0 != 6 ) ){
                if( $c1 < 5 ){
                    $ary1[$i]['capital']="美黄金";
                }
            }
            $ary1[$i]['direction'] = 1;
            if( $c2 < 5 ){
                $ary1[$i]['direction']="0";
            }

            $ary1[$i]['direction'] = 1;
            if( $c2 < 5 ){
                $ary1[$i]['direction']="0";
            }



        }




		$this->display();
	}
	public function index2(){

		$is_week = in_array(date("w"), array(0,6))?1:0;
		$this->assign('is_week',$is_week);

		$user = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
		$this->assign('user',$user);

		$this->display();
	}

	public function indexchart(){
	    $this->display();
	}

	public function indexchart2(){
	    $this->display();
	}
	public function chart(){
	    $this->display();
	}


    public function dice(){
        $user = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
        if($user["dice_time"] != date('Ymd')){
            $user["dice_time"] = date('Ymd');
            $user["dice_cnt"] = 10;
            M('juejin_users')->where(['id'=>$_SESSION['user_id']])->save($user);
        }
        $this->assign('user',$user);
        $this->display();
    }

	public function getoption(){
		 $array[3]=array('capital_name'=>'黄金','capital_key'=>'HJRMB');
		$array[4]=array('capital_name'=>'比特币','capital_key'=>'BTCCNY');
        $array[0]=array('capital_name'=>'美元/日元','capital_key'=>'USDJPY');
		$array[2]=array('capital_name'=>'英镑/美元','capital_key'=>'GBPUSD');
		$array[1]=array('capital_name'=>'欧元/美元','capital_key'=>'EURUSD');
		exit(json_encode($array));	
	}
	// 刷新时调用
	public function getCapitalTypes(){
		$array[0] = array('id'=>1,'trade_type'=>0,'trade_name'=>'标准','product_type'=>0,'product_key'=>'hot','product_name'=>'热门资产','capital_type'=>0,
		'capital_key'=>'EURUSD','capital_name'=>'欧元/美元','capital_time'=>0,'flag'=>1,'sort'=>3);
		
		$array[1] = array('id'=>2,'trade_type'=>0,'trade_name'=>'标准','product_type'=>0,'product_key'=>'hot','product_name'=>'热门资产','capital_type'=>0,
		'capital_key'=>'USDJPY','capital_name'=>'美元/日元','capital_time'=>0,'flag'=>1,'sort'=>1);
		
		$array[2] = array('id'=>3,'trade_type'=>0,'trade_name'=>'标准','product_type'=>0,'product_key'=>'hot','product_name'=>'热门资产','capital_type'=>0,
		'capital_key'=>'GBPUSD','capital_name'=>'英镑/美元','capital_time'=>0,'flag'=>1,'sort'=>1);
		
		$array[3] = array('id'=>1,'trade_type'=>0,'trade_name'=>'标准','product_type'=>1,'product_key'=>'cyp','product_name'=>'货币对','capital_type'=>0,
		'capital_key'=>'BTCCNY','capital_name'=>'比特币','capital_time'=>0,'flag'=>1,'sort'=>3);

        $array[4] = array('id'=>4,'trade_type'=>0,'trade_name'=>'标准','product_type'=>1,'product_key'=>'hj','product_name'=>'货币对','capital_type'=>0,
            'capital_key'=>'HJRMB','capital_name'=>'黄金','capital_time'=>0,'flag'=>1,'sort'=>3);

        $array[5] = array('id'=>5,'trade_type'=>0,'trade_name'=>'标准','product_type'=>1,'product_key'=>'by','product_name'=>'货币对','capital_type'=>0,
            'capital_key'=>'BYRMB','capital_name'=>'白银','capital_time'=>0,'flag'=>1,'sort'=>3);
		exit(json_encode($array));
		
	}
	public function get_newallorder_ajax(){
		$orderlist =  M('juejin_order')->order('id desc')->limit(100)->select();
		$pinlist=array();
		$time = time();
		$is_week = in_array(date("w"), array(0,6))?1:0;

		foreach ($orderlist as $key=>$val){
			$pinlist[$key]['id'] = $val['id'];
			$pinlist[$key]['user_id'] = $val['userid'];
			$pinlist[$key]['trade_amount'] = $val['amount'];
			$pinlist[$key]['trade_direction'] = $val['dircetion'];
			$nowtime = $time-$key*10+rand(1,12);
			$pinlist[$key]['shijian'] = date('H:i:s',$nowtime);
			if($is_week){
				$pinlist[$key]['capital_name'] ='比特币';
			}else{
				$pinlist[$key]['capital_name'] =$this->capitalNaem[$val['capital']];
			}
				
		}
		
		$list['list']=$pinlist;
		$list['live_status']=0;
	
		$list['renshu']=15632+M('juejin_order')->group('userid')->count();
		$list['status']=1;
		$list['trade_count']=46521+M('juejin_order')->count();
		
		exit(json_encode($list));
		
	
		$array[0]=array('id'=>'5','option_id'=>5,'user_id'=>53596,'proxy_id'=>0,'trade_amount'=>'200.00',
				'trade_direction'=>0,'trade_point'=>1264.14,'trade_time'=>1475740769,'finish_time'=>1475740829,
				'failed_profit'=>0.00,'expect_profit'=>370.00,'profit'=>null,'is_settle'=>0,'settle_time'=>null,
				'settle_point'=>null,'is_win'=>null,'option_key'=>'XAUUSD','trade_type'=>0,'pruduct_type'=>null,
				'bot_flag'=>0,'settle_num'=>'0000','settle_ip'=>"121.62.154.163",'minute'=>null,'is_sim'=>1,
				'is_fast'=>0,'is_control'=>0,'trade_name'=>'标准','product_type'=>0,'product_key'=>'hot','product_name'=>'热门资产',
				'capital_type'=>4,'capital_key'=>'XAUUSD','capital_name'=>'黄  金','capital_time'=>0,'flag'=>1,'sort'=>7,'shijian'=>'15:59:35');
	
		$array[1]=array('id'=>'5','option_id'=>5,'user_id'=>53596,'proxy_id'=>0,'trade_amount'=>'200.00',
				'trade_direction'=>1,'trade_point'=>1264.14,'trade_time'=>1475740769,'finish_time'=>1475740829,
				'failed_profit'=>0.00,'expect_profit'=>370.00,'profit'=>null,'is_settle'=>0,'settle_time'=>null,
				'settle_point'=>null,'is_win'=>null,'option_key'=>'XAUUSD','trade_type'=>0,'pruduct_type'=>null,
				'bot_flag'=>0,'settle_num'=>'0000','settle_ip'=>"121.62.154.163",'minute'=>null,'is_sim'=>1,
				'is_fast'=>0,'is_control'=>0,'trade_name'=>'标准','product_type'=>0,'product_key'=>'hot','product_name'=>'热门资产',
				'capital_type'=>4,'capital_key'=>'XAUUSD','capital_name'=>'黄  金','capital_time'=>0,'flag'=>1,'sort'=>7,'shijian'=>'15:59:34');
	
		$array[2]=array('id'=>'5','option_id'=>5,'user_id'=>53596,'proxy_id'=>0,'trade_amount'=>'200.00',
				'trade_direction'=>1,'trade_point'=>1264.14,'trade_time'=>1475740769,'finish_time'=>1475740829,
				'failed_profit'=>0.00,'expect_profit'=>370.00,'profit'=>null,'is_settle'=>0,'settle_time'=>null,
				'settle_point'=>null,'is_win'=>null,'option_key'=>'XAUUSD','trade_type'=>0,'pruduct_type'=>null,
				'bot_flag'=>0,'settle_num'=>'0000','settle_ip'=>"121.62.154.163",'minute'=>null,'is_sim'=>1,
				'is_fast'=>0,'is_control'=>0,'trade_name'=>'标准','product_type'=>0,'product_key'=>'hot','product_name'=>'热门资产',
				'capital_type'=>4,'capital_key'=>'XAUUSD','capital_name'=>'黄  金','capital_time'=>0,'flag'=>1,'sort'=>7,'shijian'=>'15:59:33');
	
		$array[3]=array('id'=>'5','option_id'=>5,'user_id'=>53596,'proxy_id'=>0,'trade_amount'=>'200.00',
				'trade_direction'=>1,'trade_point'=>1264.14,'trade_time'=>1475740769,'finish_time'=>1475740829,
				'failed_profit'=>0.00,'expect_profit'=>370.00,'profit'=>null,'is_settle'=>0,'settle_time'=>null,
				'settle_point'=>null,'is_win'=>null,'option_key'=>'XAUUSD','trade_type'=>0,'pruduct_type'=>null,
				'bot_flag'=>0,'settle_num'=>'0000','settle_ip'=>"121.62.154.163",'minute'=>null,'is_sim'=>1,
				'is_fast'=>0,'is_control'=>0,'trade_name'=>'标准','product_type'=>0,'product_key'=>'hot','product_name'=>'热门资产',
				'capital_type'=>4,'capital_key'=>'XAUUSD','capital_name'=>'黄  金','capital_time'=>0,'flag'=>1,'sort'=>7,'shijian'=>'15:59:32');
	
		$array[4]=array('id'=>'5','option_id'=>5,'user_id'=>53596,'proxy_id'=>0,'trade_amount'=>'200.00',
				'trade_direction'=>1,'trade_point'=>1264.14,'trade_time'=>1475740769,'finish_time'=>1475740829,
				'failed_profit'=>0.00,'expect_profit'=>370.00,'profit'=>null,'is_settle'=>0,'settle_time'=>null,
				'settle_point'=>null,'is_win'=>null,'option_key'=>'XAUUSD','trade_type'=>0,'pruduct_type'=>null,
				'bot_flag'=>0,'settle_num'=>'0000','settle_ip'=>"121.62.154.163",'minute'=>null,'is_sim'=>1,
				'is_fast'=>0,'is_control'=>0,'trade_name'=>'标准','product_type'=>0,'product_key'=>'hot','product_name'=>'热门资产',
				'capital_type'=>4,'capital_key'=>'XAUUSD','capital_name'=>'黄  金','capital_time'=>0,'flag'=>1,'sort'=>7,'shijian'=>'15:59:31');
	
	
	
		$list['list']=$array;
		$list['live_status']=0;
		$list['renshu']=371914;
		$list['status']=1;
		$list['trade_count']=2303491;
	
		exit(json_encode($list));
	
	
	}
	public function getSameUser(){
		
		
		exit(json_encode(array(false)));
	}

	public function getlastdealtime(){
	    $userid = I("userid");
	    $sql =  "select max( createtime ) as ma from sp_juejin_order where userid =".$_SESSION['user_id'];
        $reuslt1 = M("juejin_order")->query( $sql );
        $result2 = $result1[0];
        $result3 = $result2['ma'];
        $this->ajaxReturn( $result3 );
	}

	/*创建订单*/
	public function deal_dq(){
         
		/* amount:5000
		trade_time:60
		capital:BTCCNY
		product:hot
		dircetion:1
		sec:60秒
		deal_value:
		yield:undefined
		expect_profit:9000
		faild_profit:undefined */
		/*每个玩家下单的时间间隔必须超过20秒*/
		$data['capital']=I("capital");
		$countsql = "select max( createtime ) as maxx from sp_juejin_order where capital = '".$data['capital']."' and userid =".$_SESSION['user_id'];


        $reuslt11 = M("juejin_order")->query( $countsql );
//        file_put_contents("deal_dq.txt","\r\n",FILE_APPEND);
//        file_put_contents("deal_dq.txt",M("juejin_order")->getLastSql(),FILE_APPEND);

        if( time()-$reuslt11[0][maxx] < 20  )
        {
            $this->ajaxReturn(['error'=>'订单创建失败，时间间隔必须大于20秒！','type'=>'error']);
        }
        if( I("capital") =="NECLA0" )
        {
            if(( date('w') == 6) || (date('w')==0)){
                //$this->ajaxReturn(['error'=>'The weekend is closed for gold','type'=>'error']);
                $this->ajaxReturn(['error'=>'                黄金周末休市','type'=>'error']);
            }
        }


		$_SESSION['is_sim'] = 1;
		
		$user = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
		if($_SESSION['user_id'] == false || !$user){
			$this->ajaxReturn(['error'=>'登录失效，请刷新登录','type'=>'error']);
		}
		$is_sim = $_SESSION['is_sim']?$_SESSION['is_sim']:0;
		$key = ($is_sim==1)?'money':'coin';
		
		if($user[$key]<I("amount")){
			$this->ajaxReturn(['error'=>'账户余额不足，请充值！','type'=>'error']);
		}
		
		
		//
		$data['userid']=$_SESSION['user_id'];
		$data['phone']=$_SESSION['user_phone'];
		$data['createtime']=time();/*创建时间*/
		$data['capital']=I("capital");
		$data['amount']=I("amount");
		$data['dircetion']=I("dircetion");
		$data['deal_value']=I("deal_value");
		/*60秒。*/
		$trade_time = I('trade_time');
		$data['trade_time']=I('trade_time');
		
//		switch (I('trade_time')){
//			case 150:
//				$data['get_amount']=I("amount")*1.75;
//				break;
//			case 120:
//				$data['get_amount']=I("amount")*1.8;
//				break;
//			case 60:
//				$data['get_amount']=I("amount")*1.85;
//				break;
//		}

		$data['get_amount'] = I("expect_profit");
		
		$data['is_sim']=$is_sim;
		$data['user_zyj']=$_SESSION['user_zyj']?$_SESSION['user_zyj']:0;
		if($data['user_zyj']>0){
			$_SESSION['user_zyj']=0;
			M('juejin_users')->where(['id'=>$_SESSION['user_id']])->setDec('xulimoney',I("amount")*0.1);
		}

        /*减去了2%的手续费*/
	    $atmp = floatval(I("amount")) * 1.02;

		if(M('juejin_users')->where(['id'=>$_SESSION['user_id']])->setDec($key,$atmp )){
			$newuser = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
			$id = M('juejin_order')->add($data);
			$date['error']='';
			$date['type']='success';
			$date['amount']=I("amount");
			$date['direction']=I('dircetion');//1涨 0 亏
			$date['deal_value']=I("deal_value");
			$date['user_deal_time']=time();// 下单时间
			$date['time_dif']=0;
			$date['capital']=I("capital");
			$date['id']=$id;
			$date['usermoney']=$newuser['money'];
			$date['sim_money']=$newuser['coin'];
			$date['e_price']=null;
			$date['e_is']=null;
			$date['fate']=0.15;



			/*创建订单成功后，要创建一级返利订单*/
            $setting = M('juejin_set')->find(1);
			if( $newuser['shareid'] != 0 )
			{
                $flo = array();
                $flo['userid'] = $_SESSION['user_id'];
                $flo['wechat_id'] = $this->wechat_id;
                $flo['touserid'] = $newuser['shareid'];
                $flo['price'] = $setting['first']*$date['amount']/100;
                $flo['status'] = 0;
                $flo['remark'] = '1级返利';
                $flo['createtime'] = time();
                M('juejin_fanliorder')->add($flo);

                /*查找本用户的上上级*/
                $suser = M('juejin_users')->where(['id'=>$newuser['shareid']])->find();//
                file_put_contents("deal_dq.txt", M('juejin_users')->getLastSql()."\r\n",FILE_APPEND);
                if( $suser['shareid'] != 0 )
                {
                    /*说明本用户有上上级*/
                    $flo = array();
                    $flo['userid'] = $_SESSION['user_id'];
                    $flo['wechat_id'] = $this->wechat_id;
                    $flo['touserid'] = $suser['shareid'];
                    $flo['price'] = $setting['second']*$date['amount']/100;
                    $flo['status'] = 0;
                    $flo['remark'] = '2级返利';
                    $flo['createtime'] = time();
                    M('juejin_fanliorder')->add($flo);
                }
             }


			$this->ajaxReturn($date);

		}
		else{
			$this->ajaxReturn(['error'=>'订单创建失败，请联系客服！','type'=>'error']);	
		}
	}

	public function tete(){
        $sql = "select max( createtime ) as maxx from sp_juejin_order where userid =".$_SESSION['user_id'];
        $reuslt1 = M("juejin_order")->query( $sql );
        print_r( $reuslt1 );

        $result2 = $reuslt1[0];
        print_r( $result2 );
        echo "<br/>";
        print_r( $result2['maxx'] );
	}

	/*首页的交易列表的伪造数据*/
	public function gettradelist(){
	    $sdata = array();
	    /*搜索数据库里面的真实交易数据*/
        $sql = "select dircetion,capital,is_win,amount,createtime as tim from sp_juejin_order where createtime > ".(time()-5)." limit 0,1";
        $query = M("juejin_order")->query( $sql );


        if( count($query) > 0 )
        {

            $sdata['buy'] = "买跌";
            if( $query[0]['dircetion'] == "1" )
            {
                 $sdata['buy'] = "买涨";
            }

            $sdata['name']="比特币";
            if( $query[0]['dircetion'] == "NECLA0" )
            {
                $sdata['name']="美黄金";
            }

            $sdata['buy_state'] = 1;
            if( $query[0]['is_win'] == 0 )
            {
                $sdata['buy_state'] = -1;
            }

            $sdata['price'] = $query[0]['amount'];

            $sdata['time'] = date( "H:i:s", $query[0]['tim'] );
            $sdata['iftrue'] = "actual";

            $this->ajaxReturn( $sdata );
            exit();

        }


        $c1 = rand(1,10);//生成1到10的整数随机数
        $c2 = rand(1,10);//生成1到10的整数随机数
        $c3 = rand(1,10);//生成1到10的整数随机数
        $c4 = rand(1,100);//生成1到100的整数随机数
        $d0 = date('w');
        $sdata['buy'] = "买跌";
        if( $c1 <= 5 )
        {
            $sdata['buy'] = "买涨";
        }

        $sdata['name']="比特币";
        if( ( $d0 != 0 ) && ( $d0 != 6 ) )
        {
            if( $c2 <= 5 )
            {
                $sdata['name']="美黄金";
            }
        }

        $sdata['buy_state'] = 1;
        if( $c3 <= 5 )
        {
            $sdata['buy_state'] = -1;
        }
        
        if( $c4 > 95 )
        {
            $sdata['price'] = 5000;
        }else if( $c4 > 65 && $c4 <= 95 )
        {
            $sdata['price'] = 3000;
        }else if( $c4 >45 && $c4 <= 65 )
        {
            $sdata['price'] = 2000;
        }else if( $c4 > 25 && $c4 <= 45 )
        {
            $sdata['price'] = 1000;
        }else if( $c4 > 5 && $c4 <= 20 )
        {
            $sdata['price'] = 500;
        }else{
            $sdata['price'] = 100;
        }

        $sdata['time'] = date( "H:i:s", time() );

        $sdata['iftrue'] = "hypocritical";


        $this->ajaxReturn( $sdata );


	}

    private function getDiceArr($dir){
        $c1 = rand(1,6);
        $c2 = rand(1,6);
        $c3 = rand(1,6);
        if($dir == 0){

            while($c1 + $c2 + $c3 >= 11){
                $c1 = rand(1,6);
                $c2 = rand(1,6);
                $c3 = rand(1,6);
            }
            return array($c1,$c2,$c3);
        }
        else{
            while($c1 + $c2 + $c3 < 11){
                $c1 = rand(1,6);
                $c2 = rand(1,6);
                $c3 = rand(1,6);
            }
            return array($c1,$c2,$c3);
        }
    }

    public function deal_dice(){

        /* amount:5000
        trade_time:60
        capital:BTCCNY
        product:hot
        dircetion:1
        sec:60秒
        deal_value:
        yield:undefined
        expect_profit:9000
        faild_profit:undefined */

        $user = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
        if($_SESSION['user_id'] == false || !$user){
            $this->ajaxReturn(['error'=>'登录失效，请刷新登录','type'=>'error']);
        }
        $is_sim = 1;
        $key = 'money';

        if($user[$key]<I("amount")){
            $this->ajaxReturn(['error'=>'账户余额不足，请充值！','type'=>'error']);
        }

        // 检查用户今天是否玩过10次
        if($user["dice_cnt"] < 1 && $user["dice_time"] == date("Ymd")){
            $this->ajaxReturn(['error'=>'今天已经玩够10次，请明天再来！','type'=>'error']);
        }

        //
        $data['userid']=$_SESSION['user_id'];
        $data['phone']=$_SESSION['user_phone'];
        $data['createtime']=time();
        $data['capital']=I("capital");
        $data['amount']=I("amount");
        $data['dircetion']=I("dircetion");
        $data['deal_value']=I("deal_value");
        $data['trade_time']=I('trade_time');
        $data['type'] = 1;
        $data['get_amount']=I("amount");

        $result = array("points"=>"", "result"=> 0);
        //判断是否输赢，然后决定是增加还是减少金额
        $isWin = false;
        //todo:
        $suc_rand = rand(1,99);
        if($suc_rand <= 50){
            // 输
            if(I("dircetion") == 0){
                // 客户选小，就返回大
                $arr = $this->getDiceArr(1);
                $result["points"] = join("-", $arr);
                $result["result"] = 1;
            }
            else{
                // 客户选大，就返回小
                $arr = $this->getDiceArr(0);
                $result["points"] = join("-", $arr);
                $result["result"] = 0;
            }
        }
        else{
            $isWin = true;
            // 赢
            if(I("dircetion") == 0){
                // 客户选小，就返回小
                $arr = $this->getDiceArr(0);
                $result["points"] = join("-", $arr);
                $result["result"] = 0;
            }
            else{
                // 客户选大，就返回大
                $arr = $this->getDiceArr(1);
                $result["points"] = join("-", $arr);
                $result["result"] = 1;
            }
        }

        $data['is_sim']=$is_sim;
        $data['user_zyj']= 0;

        $ok = false;
        if($isWin){
            $ok = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->setInc($key,I("amount"));
        }
        else{
            $ok = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->setDec($key,I("amount"));
        }
        if($ok){
            $newuser = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
            $newuser["dice_cnt"] = $newuser["dice_cnt"] - 1;
            $newuser["dice_time"] = date("Ymd");
            M('juejin_users')->where(['id'=>$_SESSION['user_id']])->save($newuser);

            $id = M('juejin_order')->add($data);
            $result["money"] = $newuser["money"];
            $result["dice_cnt"] = $newuser["dice_cnt"];
            $date['error']='';
            $date['type']='success';
            $date['data'] = $result;
            $this->ajaxReturn($date);
        }
        else{
            $this->ajaxReturn(['error'=>'订单创建失败，请联系客服！','type'=>'error']);
        }

    }


    /*获得持仓订单*/
	public function get_open_orders(){
        $is_sim = $_SESSION['is_sim']?$_SESSION['is_sim']:0;
        $data['is_sim']=$is_sim;
        $data['status']=1;
        $page = I('page')?I('page'):1;
        $limit =( ($page-1)*15).',15';
        $now=time();
//        $timewhere['createtime'] = array('gt',$now - 10*60);//10分钟内的订单


//        $yssql = "select * from( select *,(createtime+trade_time)as ttii from sp_juejin_order where userid = ".$_SESSION['user_id']." and is_sim = 1 order by id desc)a where and ttii <= ".$now." limit 0,15";
$yssql = "select * from (select *,createtime+trade_time as ttii from sp_juejin_order where userid=".$_SESSION['user_id']." and is_sim = 1 order by id desc)a where a.ttii >= ".$now." limit 0,15";

        $list = M('juejin_order')->query( $yssql );
//        $this->ajaxReturn( M('juejin_order')->getLastSql() );
//        $this->ajaxReturn(  $list  );
        if(empty($list)){
            $this->ajaxReturn('no');
            $this->ajaxReturn(['status'=>'no']);
        }
        $orderlist = array();
        foreach ($list as $key=>$val) {
            if ($val['createtime'] + $val['trade_time'] <= $now) {
                /*非持仓订单*/
                continue;
            }
            $orderlist[$key]['id'] = $val['id'];
            $orderlist[$key]['trade_amount'] = $val['amount'];
            $orderlist[$key]['expect_profit'] = $val['get_amount'];
            $orderlist[$key]['trade_direction'] = ($val['capital'] == 'DICE') ? $this->capitalNaem[$val['dircetion']] : (($val['dircetion'] == 1) ? '涨' : '跌');
            $orderlist[$key]['trade_point'] = number_format($val['deal_value'], 2, '.', ',');
            $orderlist[$key]['trade_time'] = date('m-d H:i:s', $val['createtime']);
            $orderlist[$key]['option_key'] = $this->capitalNaem[$val['capital']];
			 $orderlist[$key]['trade_type'] = 1;
            if ($val['createtime'] + $val['trade_time'] > $now) {
                $orderlist[$key]['is_settle'] = '未结算';
            } else {               
                $orderlist[$key]['is_settle'] = $val['is_win'] ? '<font color=red>盈利</font>' : '<font color=green>亏损</font>';//
            }
        }
        $data['list']=$orderlist;


//        $this->ajaxReturn(count( $data['list'] ));
        $this->ajaxReturn($data);
	}

	/*获得最近的已成交订单*/
	public function get_now_orders(){
    		/* $type =I('type');//XAUUSD
    		$date['is_sim']=1;
    		$date['status']=1;
    		$date['list'][]= array('id'=>6377845,'expect_profit'=>3700.00,'finish_time'=>'10-13 10:32:28',
    				'is_settle'=>'未结算','option_key'=>'黄  ','settle_time'=>'01-01 08:00:00','trade_amount'=>2000.00,
    				'trade_direction'=>'买涨','trade_point'=>1258.67,'trade_time'=>'10-13 10:31:28','trade_type'=>1
    		);
    		$this->ajaxReturn($date); */

            $is_sim = $_SESSION['is_sim']?$_SESSION['is_sim']:0;
            $data['is_sim']=$is_sim;
            $data['status']=1;
            $page = I('page')?I('page'):1;
            $limit =( ($page-1)*15).',15';
            $now=time();
//            $this->ajaxReturn($_SESSION['user_id']);
//            $timewhere['createtime'] = array('gt',$now - 10*60);//10分钟内的订单
            $list = M('juejin_order')->where(['userid'=>$_SESSION['user_id'],'is_sim'=>$is_sim])->limit($limit)->order('id desc')->select();

            $sql = M('juejin_order')->getLastSql();
//            $this->ajaxReturn($sql);

            if(empty($list)){
                $this->ajaxReturn(['status'=>'no']);
            }

            $orderlist = array();
            foreach ($list as $key=>$val) {
                if ($val['createtime'] + $val['trade_time'] > $now) {
                    /*这个逻辑分枝代表的是持有订单*/
                    continue;
                }
                $orderlist[$key]['id'] = $val['id'];
                $orderlist[$key]['trade_amount'] = $val['amount'];
                $orderlist[$key]['expect_profit'] = $val['get_amount'];
                $orderlist[$key]['trade_direction'] = ($val['capital'] == 'DICE') ? $this->capitalNaem[$val['dircetion']] : (($val['dircetion'] == 1) ? '买涨' : '买跌');
                $orderlist[$key]['trade_point'] = number_format($val['deal_value'], 2, '.', ',');
                $orderlist[$key]['trade_time'] = date('m-d H:i:s', $val['createtime']);
                $orderlist[$key]['option_key'] = $this->capitalNaem[$val['capital']];
    			 $orderlist[$key]['trade_type'] = 1;
                if ($val['createtime'] + $val['trade_time'] > $now) {
                    $orderlist[$key]['is_settle'] = '未结算';
                } else {
                    $orderlist[$key]['is_settle'] = $val['is_win'] ? '<font color=red>盈利</font>' : '<font color=green>亏损</font>';//
                }
            }
            $data['list']=$orderlist;


            $this->ajaxReturn($data);
    	}



    public function get_now_money(){
        $user = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
        if( $user != null )
        {
             $this->ajaxReturn($user['money']);
        }
    }


	/*public function get_history_ajax(){
		$id = I('id');
		$type=I('type');//1 flow_span_value
		$order = M('juejin_order')->find($id);
		$user = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
		
		$deal_value =I("deal_value");
		$rand= rand(-15,15)/100;
		if(!$deal_value){
			$isdir  = ($order['direction']==1)?1:-1;
			$deal_value = $order['deal_value'] + $rand*$isdir;
		}
		$is_sim = $_SESSION['is_sim']?$_SESSION['is_sim']:0;
		
		$key = ($is_sim==1)?'money':'coin';
		
		if( (($deal_value-$order['deal_value'])>0 && $order['dircetion']==1) || (($deal_value-$order['deal_value'])<0 && $order['dircetion']==0) ){
			$date['is_win']=1;	

			if($order['user_zyj']>0){
				$date['profit']=($order['amount']+$order['amount']*0.1)*0.85;
			}
			$date['profit']=$order['get_amount'];
			
			
			M('juejin_users')->where(['id'=>$_SESSION['user_id']])->setInc($key,$date['profit']);
			M('juejin_order')->where(['id'=>$order['id']])->save(['is_win'=>1,'type'=>1,'end_value'=>$deal_value]);
			
		
			
			$newuser = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
			$date['money']=$newuser['money'];
			$date['sim_money']=$newuser['coin'];
		}
		else{
			$date['is_win']=0;
			$date['profit']=$order['amount'];
			$date['money']=$user['money'];
			$date['sim_money']=$user['coin'];
			M('juejin_order')->where(['id'=>$order['id']])->save(['is_win'=>0,'type'=>1,'end_value'=>$deal_value]);
		}
		
		$date['is_sim']=$is_sim;
		$date['close']=$deal_value;
		
		$date['Klinetime']=$order['createtime']+60;
		$date['capital_name']=$this->capitalNaem[$order['capital']];
		$date['option_key']=$order['capital'];
		$date['expect_profit']=$order['get_amount'];
		$date['failed_profit']=$order['amount'];
		
		$date['finish_time']=$order['createtime']+60;
		$date['id']=$order['id'];
		$date['trade_amount']=$order['amount'];
		$date['trade_direction']=$order['direction'];
		
		$date['trade_point']=$order['deal_value'];//开始价格
		$date['trade_time']=$order['createtime'];
		$date['trade_type']='1';
		$date['user_id']=$_SESSION['user_id'];//6376396
		$date['settle_point']=$deal_value;
		
		
		
		$date['high']='1256.06';
		$date['is_settle']=1;
		$date['low']='1255.87';
		
		$date['open']='1255.89';
		$date['option_id']='5';
		
		$date['proxy_id']='0';
		$date['pruduct_type']=null;
		$date['status']='1';
		
		
		
		exit(json_encode($date));
		
	}*/




    public function whetherover(){
        // 求尚未结算但时间已经到了的订单
        $id = I("id")?I("id"):0;//当前价格
        if( $id == 0 ){
            $sql = "select * from sp_juejin_order where (createtime+trade_time) < unix_timestamp() and type = 0;";
        }else{
            $sql = "select * from sp_juejin_order where id = ".$id." and (createtime+trade_time) < unix_timestamp() and type = 0;";
        }
        $list1 = M("juejin_order")->query( $sql );
        for( $i = 0; $i < count($list1); $i++ )
        {
            decidewinorlose( $list1[$i]['id'] );
        }
    }


    /*判断输赢的地方*/
	public function get_history_ajax(){
		$id = I('id');
		$type=I('type');//1 flow_span_value
		$order = M('juejin_order')->find($id);
		$user = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
		$deal_value =I("deal_value")?I("deal_value"):$order['deal_value'];//当前价格
		$is_sim = $_SESSION['is_sim']?$_SESSION['is_sim']:0;

        // 网络延迟导致,  输赢已定的情况,已结算
		if($order["type"] == 1){
            $newuser = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
            $date['is_win']=$newuser['is_win'];   /*输了*/
            $date['money']=$newuser['money'];
            $date['sim_money']=$newuser['coin'];
            $date['profit']=$order['amount'];
            $date['sim_money']=$user['coin'];

            $date['is_sim']=$is_sim;
            $date['close']=$order["end_value"];

            $date['Klinetime']=$order['createtime']+60;
            $date['capital_name']=$this->capitalNaem[$order['capital']];
            $date['option_key']=$order['capital'];
            $date['expect_profit']=$order['get_amount'];
            $date['failed_profit']=$order['amount'];

            $date['finish_time']=$order['createtime']+60;
            $date['id']=$order['id'];
            $date['trade_amount']=$order['amount'];
            $date['trade_direction']=$order['dircetion'];

            $date['trade_point']=$order['deal_value'];//开始价格
            $date['trade_time']=$order['createtime'];
            $date['trade_type']='1';
            $date['user_id']=$_SESSION['user_id'];//6376396
            $date['settle_point']=$order["end_value"];


            $date['high']='1256.06';
            $date['is_settle']=1;
            $date['low']='1255.87';
            $date['open']='1255.89';
            $date['option_id']='5';
            $date['proxy_id']='0';
            $date['pruduct_type']=null;
            $date['status']='1';
            exit(json_encode($date));
        }





		$setting = M('juejin_set')->find(1);

        /*每个玩家前五次的胜率为80%*/
        $countsql = "select count(1) as coun from sp_juejin_order where userid=".$order['userid'];
        $result1 = M("juejin_order")->query( $countsql );
        $result2 = $result1[0]['coun'];
        if( $result2 <= 5 )
        {
            $setting['suc_true'] = 80;
        }
        /*前五次的胜率调整END*/


		$end_value = 0;
		/*status为1说明开启控制*/
		if($setting['status']==1){
			$suc_rand = rand(1,99);
			switch ($order['capital']){
				case 'GBPUSD'://英镑美元
					$buy_rand =rand(1,5)/10000;
					break;
				case 'USDJPY'://美元日元
					$buy_rand =rand(1,5)/1000;
					break;
				case 'EURUSD'://欧元美元
					$buy_rand =rand(1,5)/10000;
					break;
				case 'BTbtccny':
					$buy_rand =rand(1,5)/100;
					break;
                case 'HJRMB'://黄金人民币
                    $buy_rand =rand(1,5)/1000;
                    break;
                case 'CMGCA0'://白银人民币   美白银
                    $buy_rand =rand(1,5)/1000;
                    break;
                case 'NECLA0'://美燃油
                    $buy_rand =rand(1,5)/1000;
                    break;
			}

			if($is_sim==1){//实盘
			/*在后台配置好的实盘成功率小于随机数*/
			/*这段代码的作用是根据输赢来计算end_value*/
				if($setting['suc_true']<$suc_rand){//失败
					if($order['dircetion']==1){//涨
						($deal_value<$order['deal_value'])?($end_value = $deal_value):($end_value = $order['deal_value'] -$buy_rand);
					}else{
						($deal_value<$order['deal_value'])?($end_value = $order['deal_value'] + $buy_rand):($end_value = $deal_value);
					}
				}else{//赢
					if($order['dircetion']==1){//涨
						($deal_value<$order['deal_value'])?($end_value = $order['deal_value'] + $buy_rand):($end_value = $deal_value);
					}else{
						($deal_value<$order['deal_value'])?($end_value = $deal_value):($end_value = $order['deal_value'] - $buy_rand);
					}
				}
			}else{
			/*模拟盘*/
				if($setting['suc_xu']<$suc_rand){//shibai
					if($order['dircetion']==1){//涨
						($deal_value<$order['deal_value'])?($end_value = $deal_value):($end_value = $order['deal_value'] -$buy_rand);
					}else{
						($deal_value<=$order['deal_value'])?($end_value = $order['deal_value'] + $buy_rand):($end_value = $deal_value);
					}
				}else{//赢
					if($order['dircetion']==1){//涨
						($deal_value<=$order['deal_value'])?($end_value = $order['deal_value'] + $buy_rand):($end_value = $deal_value);
				
					}else{
						($deal_value<$order['deal_value'])?($end_value = $deal_value):($end_value = $order['deal_value'] - $buy_rand);
					}
				}
			}
			/*模拟盘结束*/
		}else{
			$end_value = $deal_value;
		}
		$key = ($is_sim==1)?'money':'coin';

        //exit($tmp);

		if( (($end_value-$order['deal_value'])>0 && $order['dircetion']==1)|| (($end_value-$order['deal_value'])<0 && $order['dircetion']==0) ){
			$date['is_win']=1;

			$date['profit']=$order['get_amount'];	
			M('juejin_users')->where(['id'=>$_SESSION['user_id']])->setInc($key,$date['profit']);
			file_put_contents("apdsy.txt",M('juejin_users')->getLastSql(),FILE_APPEND);
			file_put_contents("apdsy.txt","\r\n",FILE_APPEND);
			M('juejin_order')->where(['id'=>$order['id']])->save(['is_win'=>1,'type'=>1,'end_value'=>$end_value]);
				
			$newuser = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
			$date['money']=$newuser['money'];
			$date['sim_money']=$newuser['coin'];
		}
		else{
			$date['is_win']=0;
			$date['profit']=$order['amount'];
			$date['money']=$user['money'];
			$date['sim_money']=$user['coin'];
			M('juejin_order')->where(['id'=>$order['id']])->save(['is_win'=>0,'type'=>1,'end_value'=>$end_value]);
		}
	
		$date['is_sim']=$is_sim;
		$date['close']=$end_value;
	
		$date['Klinetime']=$order['createtime']+60;
		$date['capital_name']=$this->capitalNaem[$order['capital']];
		$date['option_key']=$order['capital'];
		$date['expect_profit']=$order['get_amount'];
		$date['failed_profit']=$order['amount'];
	
		$date['finish_time']=$order['createtime']+60;
		$date['id']=$order['id'];
		$date['trade_amount']=$order['amount'];
		$date['trade_direction']=$order['dircetion'];
	
		$date['trade_point']=$order['deal_value'];//开始价格
		$date['trade_time']=$order['createtime'];
		$date['trade_type']='1';
		$date['user_id']=$_SESSION['user_id'];//6376396
		$date['settle_point']=$end_value;
	
		
		$date['high']='1256.06';
		$date['is_settle']=1;
		$date['low']='1255.87';
		$date['open']='1255.89';
		$date['option_id']='5';
		$date['proxy_id']='0';
		$date['pruduct_type']=null;
		$date['status']='1';

		exit(json_encode($date));
	}


	
	public function lastKlineParameter(){
		$capitalType = I('capitalType');
		$where['type']= $capitalType;
		
		switch ($capitalType){
			case 'BTCCNY':
				$add_rand = rand(-5,5)/100;
				break;
			case 'GBPUSD'://英镑美元
				$add_rand = rand(-5,5)/10000;
				
				break;
			case 'USDJPY'://美元日元
				$add_rand = rand(-5,5)/1000;
				
				break;
			case 'EURUSD'://欧元美元
				$add_rand = rand(-5,5)/10000;
				
				break;
            case 'HJRMB'://黄金人民币
                $add_rand = rand(-5,5)/1000;

                break;
            case 'BYRMB'://白银人民币
                $add_rand = rand(-5,5)/1000;

                break;
		}

		$info = M("juejin_msg")->where($where)->order('id desc')->find();
		$time = strtotime(date('Ymd H:i'));
		$info['buy'] = $info['buy']+$add_rand;
		$data=[$time,$info['buy'],$capitalType,I('diff'),0];
		$this->ajaxReturn($data);		
	}
	// 刷新时调用
	public function klineChart(){
		$capitalType = I('capitalType');
        $diff=I('diff');
		$where['type']= $capitalType;
		$where['createtime']= array('gt',time()-30*$diff);

		$list = M("juejin_minmsg")->where($where)->order('id asc')->select();	
		switch ($capitalType){
			case 'BTCCNY':
				$decimalPoint = 2;
				$print = "%.2f";
				break;
			case 'GBPUSD'://英镑美元
				$decimalPoint = 4;
				$print = "%.4f";
				break;
			case 'USDJPY'://美元日元
				$decimalPoint = 3;
				$print = "%.3f";
				break;
			case 'EURUSD'://欧元美元
				$decimalPoint = 4;
				$print = "%.4f";
				break;
            case 'HJRMB'://黄金人民币
                $decimalPoint = 3;
                $print = "%.3f";
                break;
            case 'BYRMB'://白银人民币
                $decimalPoint = 3;
                $print = "%.3f";
                break;
		}
		foreach ($list as $key=>$val){
			$date[$key][]=$val['createtime'];
			$date[$key][]=sprintf($print, $val['buy']);
			$date[$key][]=sprintf($print, $val['last']); //$val['last'];//$val['low'];
			$date[$key][]=sprintf($print, $val['high']);// $val['high'];
			$date[$key][]=sprintf($print, $val['low']); //$val['low'];
			$date[$key][]=0;
		}

		$data['data']=$date;
		$data['decimalPoint']=$decimalPoint;
		$data['capitalType']=$capitalType;
		$data['diff']=$diff;
		$this->ajaxReturn($data);
	}

    public function jueshengquan(){
        $user = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
        $ads = M('juejin_ad')->order('sort')->select();
        $this->assign('user',$user);
        $this->assign('ads', $ads);
        $this->display();
    }

    public function timeline(){
        $user = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
        $config = $this->getWxShareConfig();
        $this->assign('user',$user);
        $this->assign('config',$config);
        $this->display();
    }

    public function post_content(){
        $uid = I('uid');
        $user = M('juejin_users')->where(['id'=>$_SESSION['user_id']])->find();
        $date['uid'] = $uid;
        $arr = json_decode(htmlspecialchars_decode(I("serverId")));
        $config = $this->getWxConfig();
        $util =  new \Spark\Wechat\WechatUtil($config['appid'],$config['appsecret']);
        $serverIds = [];
        foreach ($arr as $id){
            \Think\Log::write("serverId:".$id);
            $path = $util->downloadWXImg($id);
            array_push($serverIds, $path);
        }
        $date["uname"] = $user["wechat_name"];
        $date["headImgUrl"] = $user["headimgurl"];
        $date['serverId'] = join(",", $serverIds);
        $date['Content'] = I("content");
        $date['likes'] = 0;
        $date['status'] = 0;
        $date['create_time']= time();
        $res = M("juejin_content")->add($date);
        if($res){
            $this->ajaxReturn(['status'=>'1','Code'=>'','info'=>'success']);
        }
        $this->ajaxReturn(['status'=>'0','Code'=>'','info'=>'发表失败']);
    }

    public function get_js_list(){
        $page = I("page");
        $start = 10 * ($page - 1);
        $result = M("juejin_content")->where(['status'=>'1'])->order('id DESC')->limit($start.',10')->select();
        $list = [];
        foreach ($result as $res)
        {
            $res["imglist"] = explode(",", $res["serverId"]);
            $count = count($res["imglist"]);
            $width = 100;
            if($count == 1){
                $width = 100;
            }
            else if($count == 2 || $count == 4){
                $width = 96 / 2;
            }
            else if ($count == 3 || $count == 5 || $count == 6){
                $width = 96 / 3;
            }

            $res["width"] = $width;
            $list[] = $res;
        }
        $this->assign("result", $list);
        $this->display();
    }

    public function set_likes(){
        $mid = I("aid");
        $status = I("status");
        if($status == 1){
            //增加1
            M("juejin_content")->where(["id"=>$mid])->setInc("likes", 1);
        }
        else{
            M("juejin_content")->where(["id"=>$mid])->setDec("likes", 1);
        }
    }


    protected function getWxShareConfig(){
        $config = $this->wxConfig;
        $util = new \Spark\Wechat\WechatUtil($config['appid'],$config['appsecret']);
        $data['jsapi_ticket'] = $util->getJsApiTicket();
        $data['timestamp'] = time();
        $data['noncestr'] = create_key();
        $data['url'] = C('WAP_DOMAIN').$_SERVER['REQUEST_URI'];
        $plain = 'jsapi_ticket='.$data['jsapi_ticket'].'&noncestr='.$data['noncestr'].'&timestamp='.$data['timestamp'].'&url='.$data['url'];
        $signature = sha1($plain);
        return ['appid'=>$config['appid'],'signature'=>$signature,'timestamp'=>$data['timestamp'],'noncestr'=>$data['noncestr']];
    }
	
	protected $capitalNaem = array('BTbtccny'=>'比特币','GBPUSD'=>'英镑/美元','USDJPY'=>'美元/日元','EURUSD'=>'欧元/美元','HJRMB'=>'黄金','BYRMB'=>'白银', 'DICE'=>'玩色子','NECLA0'=>'美燃油','CMGCA0'=>'美白银');//黄金-字母对比
    protected $diceNaem = array('0'=>'买小','1'=>'买大');//黄金-字母对比






}
?>
